package com.sk.seckilldemo.mq;

import com.sk.seckilldemo.entity.SeckillMessage;
import com.sk.seckilldemo.entity.request.SeckillRequest;
import com.sk.seckilldemo.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * 秒杀消息处理
 * */
@Component
@RequiredArgsConstructor
public class SeckillConsumer {
    private final OrderService orderService;
    private final RedisTemplate<String,Object> redisTemplate;

    /**
     * 处理秒杀请求队列中的请求并处理
     * */
    @RabbitListener(queues = "seckill.queue")
    public void handleSeckillMessage(SeckillMessage message){
        Integer user_id = message.getUser_id();
        Integer activityId = message.getActivityId();

        // 构造参数对象
        SeckillRequest request = new SeckillRequest();
        request.setUser_id(user_id);
        request.setActivityId(activityId);

        try{
            // 1. 创建订单
            orderService.createSeckillOrder(request);

            // 2.标记用户已参与
            String userKey = "seckill:user:" + activityId +":"+user_id;
            redisTemplate.opsForValue().set(userKey,"1", Duration.ofHours(2));
        }catch (Exception e){
            // 处理失败，恢复库存
            redisTemplate.opsForValue().increment("seckill:stock:"+activityId);
            System.out.println("秒杀订单处理失败："+e.getMessage());
        }
    }
}
